<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽">
    </el-switch>&nbsp;
    <el-button @click="batchSave" v-if="draggable">批量保存拖拽结果</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree :data="menus" :props="defaultProps"
             :expand-on-click-node="false"
             show-checkbox
             node-key="catId"
             :default-expanded-keys="expanded"
             :draggable="draggable"
             :allow-drop="allowDrop"
             @node-drop="handleDrop"
              ref="menuTree">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level<=2"
            type="text"
            size="mini"
            @click="() => append(data)">
            Append
          </el-button>
          <el-button
            v-if="node.childNodes.length==0"
            type="text"
            size="mini"
            @click="() => remove(node, data)">
            Delete
          </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => edit(data)">
            edit
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitData">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'category',
  created () {
    this.getMenus()
  },
  data () {
    return {
      PId:[],
      draggable:false,
      update:[],//保存需要更新的节点信息(兄弟节点 子节点可能变化)
      maxLevel:0,
      title: '',
      dialogType: '',//edit,add
      expanded: [],
      menus: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      dialogVisible: false,
      category: {
        name: '',
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: null,
        productUnit: null
      },
    }
  },
  methods: {
    batchDelete(){
      let checkedNodes = this.$refs.menuTree.getCheckedKeys()
      console.log(checkedNodes)
      this.$confirm(`是否批量删除【${checkedNodes}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(checkedNodes, false)
        }).then(res=>{
            this.$message.success("菜单批量删除成功!")
            this.getMenus()
        })
      }).catch(() => {
      })
    },
    batchSave(){//批量更新数据
      this.$http({
        url: this.$http.adornUrl('/product/category/update/sort'),
        method: 'post',
        data: this.$http.adornData(this.update,false)
      }).then(({data}) => {
        this.$message.success("菜单修改成功!");
        this.getMenus()
        this.expanded = this.PId
        this.update = []
        console.log(this.update)
        this.maxLevel = 0
        this.PId = []
      }).catch(() => {
      })
    },
    handleDrop(draggingNode, dropNode, dropType,ev){//拖拽完成之后执行（当前拖拽的节点 拖拽完成后的父节点 位于节点前还是节点之后）
      // 更新节点
      console.log("当前节点:",draggingNode)
      console.log("父节点:",dropNode)
      console.log("节点类型:",dropType)
      let updateChild = [] //子节点数组
      let PId = 0
      // 更新兄弟节点的排序 以及我们拖拽节点的父节点和拖拽节点的子节点
      if(dropType=='inner'){ //在父节点之间
        PId = dropNode.data.catId
     //   let PId = draggingNode.parent==null||draggingNode.parent.data.catId==undefined?0:draggingNode.parent.data.catId
        updateChild = dropNode.childNodes
      }else{//在之前或者之后
        PId = dropNode.parent==null||dropNode.parent.data.catId==undefined?0:dropNode.parent.data.catId
        updateChild = dropNode.parent.childNodes
      }
      for(let i=0;i<updateChild.length;i++){
        if(updateChild[i].data.catId==draggingNode.data.catId){//当前节点是我们拖拽的节点
          //将拖拽节点加入数组
          this.update.push({catId:draggingNode.data.catId,sort:i,catLevel:draggingNode.level,parentCid:PId})
          //递归将拖拽数组的子节点加入数组
          this.setUpdateChild(updateChild[i])
        }else{//当前节点是兄弟节点
          //更新排序
          this.update.push({catId:updateChild[i].data.catId,sort:i})
        }
      }
      this.PId.push(PId)
    },
    setUpdateChild(u){//递归将当前节点的子节点加入更新数组
      //子节点需要更新的是层级
      let nodes = u.childNodes
      for(let i=0;i<nodes.length;i++){
        this.update.push({catId:nodes[i].data.catId,catLevel:nodes[i].level})
        this.setUpdateChild(nodes[i])
      }
    },
    allowDrop(draggingNode,dropNode,type){//是否允许拖拽（当前拖拽的节点 拖拽完成后的父节点 位于节点前还是节点之后）
      //1 获取当前拖拽的子节点最大深度
      this.getMaxLevel(draggingNode);
      //2 获取当前拖拽子树的深度
      let cntLevel = this.maxLevel - draggingNode.level + 1;
      if(type=='inner') return dropNode.level+cntLevel<=3
      else return dropNode.parent.level+cntLevel<=3
    },
    getMaxLevel(draggingNode){//获取当前节点的子节点的最大深度
      if(draggingNode.level>this.maxLevel) this.maxLevel = draggingNode.level
      for(let i=0;i<draggingNode.childNodes.length;i++)  this.getMaxLevel(draggingNode.childNodes[i])
    },
    submitData () {
      if (this.dialogType == 'add') this.addCategory()
      else this.editCategory()
    },
    editCategory () {
      var {catId, icon, name, productUnit} = this.category
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        data: this.$http.adornData({catId, icon, name, productUnit}, false)
      }).then(({data}) => {
        this.$message.success('修改成功!')
        this.expanded = [this.category.parentCid]
        this.getMenus()
        this.dialogVisible = false
        this.category.name = ''
      }).catch(() => {
      })
    },
    edit (data) {
      this.title = '修改分类'
      this.dialogType = 'edit'
      this.dialogVisible = true
      //发送请求获取当前节点最新数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get'
      }).then(({data}) => {
        console.log('回显数据', data)
        this.category.name = data.data.name
        this.category.catId = data.data.catId
        this.category.icon = data.data.icon
        this.category.productUnit = data.data.productUnit
      }).catch(() => {
      })

    },
    addCategory () {
      console.log('提交的三级数据' + this.category.name)
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(this.category, false)
      }).then(({data}) => {
        this.$message.success('保存成功!')
        this.expanded = [this.category.parentCid]
        this.getMenus()
        this.dialogVisible = false
        this.category.name = ''
        //设置要展开的三级分类

      }).catch(() => {
      })
    },
    getMenus () {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get',
      }).then(({data}) => {
        this.menus = data.data
        console.log('成功获取到菜单数据...' + data.data)
      })
    },
    append (data) {
      this.category = {
        name: '',
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: null,
        productUnit: null
      }
      this.title = '添加分类'
      this.dialogType = 'add'
      this.dialogVisible = true
      console.log('append' + data.catId)
      this.category.parentCid = data.catId
      this.category.catLevel = data.catLevel * 1 + 1
    },

    remove (node, data) {
      var ids = [data.catId]
      this.$confirm(`是否删除【${data.name}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          this.expanded = [node.parent.data.catId]
          this.$message.success('删除成功!')
          console.log('删除成功!')
          this.getMenus()
        })
      }).catch(() => {

      })
    },
  }
}
</script>

<style scoped>

</style>
